package com.sheep.jvm;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

/**
 * 模拟OOM，Metaspace内存溢出的场景
 * -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 * @author lizy4
 * @date 2021/9/10 14:39
 */
public class Demo7 {
    public static void main(String[] args) {
        long count=0;
        while (true){
            System.out.println("目前创建了【"+(++count)+"】个Car的子类");
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Car.class);
            enhancer.setUseCache(false);
            enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
                if (method.getName().equals("run")) {
                    System.out.println("汽车启动之前，先进行安全检查...");
                    return methodProxy.invokeSuper(o, objects);
                } else {
                    return methodProxy.invokeSuper(o, objects);
                }
            });
            Car car = (Car)enhancer.create();
            car.run();
        }
    }

    static class Car{
        public void run(){
            System.out.println("汽车启动，开始行使...");
        }
    }
}
